/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.raspberrypi.gpio.tileswitch;

import cn.hutool.core.util.ObjUtil;
import com.pi4j.context.Context;
import com.pi4j.io.gpio.digital.DigitalInput;
import com.pi4j.io.gpio.digital.PullResistance;
import lombok.AccessLevel;
import lombok.experimental.Accessors;
import lombok.experimental.FieldDefaults;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;

/**
 * <b>(RaspberryPiDiodeLed)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2023/2/13
 */
@SuppressWarnings("unused")
@FieldDefaults(level = AccessLevel.PRIVATE)
@Accessors(chain = true)
@Controller
@Mapping("/titleSwitch/")
public class RaspberryPiTileSwitch {
    @Inject
    Context pi4j;
    DigitalInput titleSwitch;
    /** PIN 18 = BCM 24 */
    static final           int  DEFAULT_PIN             = 23;
    /** Default debounce time in microseconds */
    protected static final long DEFAULT_DEBOUNCE        = 25000;
    /** Default threshold for considering consecutive state changes as shaking. */
    protected static final int  DEFAULT_SHAKE_THRESHOLD = 3;

    @Mapping("/")
    public String tile(boolean ledStatus) {
        init();

        return "titleSwitch On";
    }

    private void init() {
        if (ObjUtil.isNull(titleSwitch)) {
            initSwitch();
        }
    }

    private void initSwitch() {
        var titleSwitchConfig = DigitalInput.newConfigBuilder(pi4j)
                .id("led")
                .name("LED Flasher")
                .address(DEFAULT_PIN)
                .debounce(DEFAULT_DEBOUNCE)
                .pull(PullResistance.PULL_DOWN)
                .provider("pigpio-digital-input");

        titleSwitch = pi4j.create(titleSwitchConfig);

        titleSwitch.addListener(e -> {

            switch (e.state()) {
                case LOW:
                    System.out.println("<<< Right <<<");
                    break;
                case HIGH:
                    System.out.println("<<< Left <<<");
                    break;
                case UNKNOWN:
                default:
                    System.out.println("<<< UNKNOWN <<<");
                    ;
            }
        });
    }

}
